package org.lemon.transport.mqtt.server.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.ipfilter.AbstractRemoteAddressFilter;
import lombok.extern.slf4j.Slf4j;
import org.lemon.transport.mqtt.server.BootNettyMqttServer;
import org.lemon.transport.mqtt.server.service.MqttTransportContext;

import java.net.InetSocketAddress;

@Slf4j
public class IpFilter extends AbstractRemoteAddressFilter<InetSocketAddress> {

    private final MqttTransportContext context;

    public IpFilter(MqttTransportContext context) {
        this.context = context;
    }

    /**
     * 是否ip可用
     *
     * @param ctx
     * @param remoteAddress
     * @return
     * @throws Exception
     */
    @Override
    protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) throws Exception {

        log.trace("[{}] Received msg: {}", ctx.channel().id(), remoteAddress);
        if (this.context.checkAddress(remoteAddress)) {
            log.trace("[{}] Setting address: {}", ctx.channel().id(), remoteAddress);
            ctx.channel().attr(BootNettyMqttServer.ADDRESS).set(remoteAddress);
            return true;
        }
        return false;
    }
}
